package cn.lsh.comparator;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

import java.util.StringTokenizer;

/**
 * 自定义排序比较器，将文件的分词数排在第一个
 */
public class HotComment2Comparator extends WritableComparator {

	public HotComment2Comparator() {
		super(Text.class, true);
	}

	@Override
	public int compare(WritableComparable a, WritableComparable b) {
		int i = compareId(a, b);
		if (i == 0) {
			//如果是同一个文件，id-count的记录放在前面
			if (a.toString().contains("_")) {
				return 1;
			} else if (b.toString().contains("_")) {
				return -1;
			}
		}
		return i;
	}

	public static int compareId(WritableComparable a, WritableComparable b) {
		StringTokenizer sza = new StringTokenizer(a.toString(), "_");
		StringTokenizer szb = new StringTokenizer(b.toString(), "_");
		String aId = "", bId = "";
		while (sza.hasMoreTokens()) {
			aId = sza.nextToken();
		}
		while (szb.hasMoreTokens()) {
			bId = szb.nextToken();
		}
		return aId.compareTo(bId);
	}
}
